﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Musi.Core.CSV
{
    public class CSVData: IEnumerable
    {
        private List<string> datas;
        public int Length => datas.Count;
        public string this[int index]
        {
            get
            {
                if (datas == null)
                    throw new System.NullReferenceException("CSV is empty!");
                if (index >= datas.Count)
                    throw new System.ArgumentOutOfRangeException("CSV is empty or index out of range!");
                return datas[index];
            }
        }

        public CSVData()
        {
            datas = new List<string>();
        }

        public CSVData(string[] data)
        {
            datas = new List<string>(data);
        }

        public void AddElement(string data)
        {
            datas.Add(data);
        }

        public string[] ToArray()
        {
            return datas.ToArray();
        }

        public string Serialize()
        {
            StringBuilder stringBuilder = new StringBuilder();
            for(int datasIndex = 0;datasIndex < datas.Count;datasIndex ++)
            {
                stringBuilder.Append(datas[datasIndex]);
                if (datasIndex != datas.Count - 1)
                    stringBuilder.Append(",");
            }

            return stringBuilder.ToString();
        }



        #region Implement Iterator Method
        public IEnumerator GetEnumerator()
        {
            return new Enumrator(ToArray());
        }

        public class Enumrator : IEnumerator
        {
            private string[] datas;
            private int position = -1;

            public object Current
            {
                get
                {
                    if (position >= datas.Length)
                        return null;
                    return datas[position];
                }
            }

            public Enumrator(string[] datas)
            {
                this.datas = datas;
            }

            public bool MoveNext()
            {
                if(position < datas.Length)
                {
                    position++;
                    return true;
                }
                return false;
            }

            public void Reset()
            {
                position = -1;
            }
        }
        #endregion
    }
}
